#include "checkboxitemdelegate.h"
#include "globaltype.h"
#include <QApplication>
#include <QMouseEvent>
#include <QPainter>
#include <QStyle>
#include <QStyleOptionButton>

void CheckBoxItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option,
                                 const QModelIndex& index) const
{
    // 创建一个副本以修改而不影响原始选项
    QStyleOptionViewItem viewOption(option);
    viewOption.state &= ~QStyle::State_HasFocus;
    QStyledItemDelegate::paint(painter, viewOption, index);

    // 如果需要绘制复选框，则手动绘制
    QStyleOptionButton checkbox;
    checkbox.state = QStyle::State_Enabled
            | (index.data(CHECK_STATE_ROLE).toInt() == Qt::Checked ? QStyle::State_On
                                                                   : QStyle::State_Off);

    // 计算复选框的居中位置
    const int W = QApplication::style()->pixelMetric(QStyle::PM_IndicatorWidth, &option);
    const int H = QApplication::style()->pixelMetric(QStyle::PM_IndicatorHeight, &option);
    checkbox.rect = QRect(option.rect.x() + (option.rect.width() - W) / 2,
                          option.rect.y() + (option.rect.height() - H) / 2, W, H);

    // 绘制复选框
    QApplication::style()->drawControl(QStyle::CE_CheckBox, &checkbox, painter);
}

bool CheckBoxItemDelegate::editorEvent(QEvent* event, QAbstractItemModel* model,
                                       const QStyleOptionViewItem& option, const QModelIndex& index)
{
    if (event->type() == QEvent::MouseButtonRelease
        && !index.data(DataRole::DISABLED_ROLE).toBool()) {
        Qt::CheckState state = static_cast<Qt::CheckState>(index.data(CHECK_STATE_ROLE).toInt());
        Qt::CheckState newState = (state == Qt::Checked) ? Qt::Unchecked : Qt::Checked;
        return model->setData(index, newState, CHECK_STATE_ROLE);
    }
    return QStyledItemDelegate::editorEvent(event, model, option, index);
}
